package com.luoyang.service.Impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.luoyang.entity.TbSpecification;
import com.luoyang.entity.TbSpecificationExample;
import com.luoyang.entity.TbSpecificationOption;
import com.luoyang.mapper.TbSpecificationMapper;
import com.luoyang.mapper.TbSpecificationOptionMapper;
import com.luoyang.service.SpecificationService;
import com.luoyang.util.PageResult;
import com.luoyang.vo.SpecificationVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SpecificationServiceImpl implements SpecificationService {
    @Autowired
    private TbSpecificationMapper tbSpecificationMapper;
    @Autowired
    private TbSpecificationOptionMapper  tbSpecificationOptionMapper;

    /**
     * 分页条件查询，specificationVo为null时表示查询全部
     * @param page
     * @param pageSize
     * @param specificationVo
     * @return
     */
    @Override
    public PageResult<TbSpecification> loadList(int page,int pageSize,SpecificationVo specificationVo) {
        List<TbSpecification> list = null;
        PageHelper.startPage(page,pageSize);
        if(specificationVo != null){
            TbSpecificationExample example = new TbSpecificationExample();
            TbSpecificationExample.Criteria criteria =  example.createCriteria();
            if(StrUtil.isNotBlank( specificationVo.getSpecName())){
                criteria.andSpecNameLike("%"+specificationVo.getSpecName()+"%");
            }
            list = tbSpecificationMapper.selectByExample(example);
        }else {
            list = tbSpecificationMapper.selectByExample(null);
        }
        PageInfo<TbSpecification> info = new PageInfo<>(list);
        return new PageResult<>(info.getList(), info.getTotal());
    }

    /**
     * 添加
     * @param specName 规格名称
     * @param specificationOption 规格选项
     * @return 是否添加成功
     */
    @Transactional
    @Override
    public int add(String specName, TbSpecificationOption specificationOption) {
        TbSpecification specification  = new TbSpecification();
        specification.setSpecName(specName);
        int count1 =  tbSpecificationMapper.insert(specification);
        if(count1 > 0){
            long latestId = tbSpecificationMapper.getLatestId();
            specificationOption.setSpecId(latestId);
            int count2 = tbSpecificationOptionMapper.insert(specificationOption);
            if(count2 >0) return 1;
        }
        return 0;
    }
}
